package com.example.shushiyunsst.fragment.main.home.child.miner22

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.album.view.grid_view.XGridLayout
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.SHOW_BUYING_PAGE_CML
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.MainFragment
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.miner22.bean.CMLIntent
import com.example.shushiyunsst.fragment.main.home.child.miner22.bean.ParentAccountBean
import com.example.shushiyunsst.fragment.main.home.child.miner22.bean.SubAccountListBean
import com.example.shushiyunsst.util.clipboard
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.example.wallet.utils.Preference
import com.example.wallet.utils.selectorIcon
import com.google.android.material.snackbar.Snackbar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import ikidou.reflect.TypeBuilder
import org.greenrobot.eventbus.EventBus
import java.lang.reflect.Type

/**
 * 子账户
 * */
class SubAccountListFragment : SimpleListFragment<SubAccountListBean>(), OnItemChildClickListener {

    companion object {
        fun newInstance(): SubAccountListFragment {
            val args = Bundle()
            val fragment = SubAccountListFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private lateinit var walletTv: TextView

    private var cmlBalance = ""

    private var cmlBalanceLock = ""

    private var arlBalance = ""


    private lateinit var mParentAddressTv: TextView

    private lateinit var mparentIcCopyIcon: ImageView

    private lateinit var scmlBalance: TextView

    private lateinit var scmlAccIncome: TextView

    private lateinit var scmlAccTotalIncome: TextView


    private lateinit var mXGridLayout: XGridLayout

    private var mXGridLayoutAdapter: CommAdapter<ParentAccountBean>? = null

    private val walletArl = AppGlobals.getApplication().getString(R.string.wallet_arl)

    private val walletCml = AppGlobals.getApplication().getString(R.string.wallet_cml)

    private var onActive = false

    private var activeScmlLockNeedCmlNums = ""

    //母币可合成数量
    private var scmlBalanceMixAvailable = ""

    //子币可合成数量
    private var cmlBalanceMixAvailable = ""

    //1 显示已激活 0 显示激活母币矿池
    private var isActiveScml=""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        isEnableLoadMore = false
        isAddDividerItemDecoration = false
    }

    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundResource(R.color.bg_color)
        mHeader.removeAllViews()
        addHeader(R.layout.comment_header_layout)
        mHeader.findViewById<View>(R.id.headerLayout).setBackgroundResource(R.color.bg_color_0)
        val mToolbar: Toolbar = mHeader.findViewById(R.id.mToolbar)
        mToolbar.title = "子账户"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        val inflate = LayoutInflater.from(_mActivity)
            .inflate(R.layout.sub_account_list_head_fragment, view as ViewGroup, false)
        mAdapter.addHeaderView(inflate)

        mXGridLayout = inflate.findViewById(R.id.mXGridLayout)

        mXGridLayoutAdapter = object : CommAdapter<ParentAccountBean>(
            _mActivity, R.layout.sub_account_list_x_item_fragment
        ) {
            override fun convert(
                holder: XQuickViewHolder?,
                item: ParentAccountBean?,
                position: Int
            ) {
                val isActiveScmlFlag=isActiveScml.contains("1")
                val mActiveStr=if (isActiveScmlFlag)"已激活" else "激活母币矿池"
                val sys = UserInfoManager.userInfoManager
                    .getUserInfoWrapper()?.userInfo?.sysWalletAddress
                val accountName = item?.accountName ?: ""
                val wallet_cml = AppGlobals.getApplication().getString(R.string.wallet_cml)
                holder?.setText(R.id.titleTv, accountName)
                    ?.setText(R.id.mAddressTv, sys)
                    ?.setText(R.id.mBalance, item?.balance.toString())
//                    ?.setText(R.id.mActiveBanalce, item?.activeBanalce.toString())
                    ?.setText(R.id.mBlockBalance, item?.lockBanalce.toString())
                    ?.setText(R.id.mAccIncome, item?.income)
                    ?.setText(R.id.mActive,mActiveStr)
//                    ?.setVisible(R.id.mBlockLayout, (item?.lockBanalce?:0.0) > 0.0)
                    ?.setText(R.id.mAccTotalIncome, item?.totalIncome.toString())
                    ?.setVisible(R.id.operation, accountName.contains(wallet_cml))
                    ?.setOnClickListener(R.id.mCompoundTv) {
                        onCompoundTv(item)
                    }
                    ?.setOnClickListener(R.id.mActive) {

                        if (isActiveScmlFlag){
                            Toast.makeText(_mActivity,"已激活母币矿池",Toast.LENGTH_SHORT).show()
                            return@setOnClickListener
                        }


                        if (!onActive) {
                            onActive = true
                            onActive(position)
                        }

                    }
                    ?.setOnClickListener(R.id.ic_copy_icon) {
                        clipboard("addressTv", sys ?: "")
                    }
                    ?.setOnClickListener(R.id.mTransfer) {
                        val address = sys ?: ""
                        val bean = CMLIntent(
                            address,
                            item?.balance.toString(),
                            item?.tokenType ?: "",
                            item?.accountType ?: "",
                            CMLIntent.MOTHER_ACCOUNT
                        )
                        start(CMLTransferFragment.newInstance(bean))
                    }
                    ?.setOnClickListener(R.id.mSouKanTv) {
                        val address = sys ?: ""
                        val bean = CMLIntent(
                            address,
                            item?.balance.toString(),
                            item?.tokenType ?: "",
                            item?.accountType ?: "",
                            CMLIntent.MOTHER_ACCOUNT
                        )
                        start(CMLCollectionFragment.newInstance(bean))
                    }
            }

        }

        mXGridLayout.setAdapter(mXGridLayoutAdapter, lifecycle)

//        addHeader(R.layout.sub_account_list_head_fragment)

        walletTv = inflate.findViewById(R.id.walletTv)
        scmlBalance = inflate.findViewById(R.id.scmlBalance)
        scmlAccIncome = inflate.findViewById(R.id.scmlAccIncome)
        scmlAccTotalIncome = inflate.findViewById(R.id.scmlAccTotalIncome)

        mParentAddressTv = inflate.findViewById(R.id.mParentAddressTv)
        mparentIcCopyIcon = inflate.findViewById(R.id.mParent_ic_copy_icon)

        val addressTv: TextView = inflate.findViewById(R.id.addressTv)
        val sys = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo?.sysWalletAddress
        addressTv.text = sys
        mParentAddressTv.text = sys
        val icCopyIcon: ImageView = inflate.findViewById(R.id.ic_copy_icon)
        icCopyIcon.setOnClickListener {
            clipboard("addressTv", sys ?: "")
        }
        mparentIcCopyIcon.setOnClickListener {
            clipboard("addressTv", sys ?: "")
        }

        //收款
        val souKanTv: View = inflate.findViewById(R.id.souKanTv)
        souKanTv.setOnClickListener {
            val address = sys ?: ""
            val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
            val invitationCode = userInfo?.invitationCode ?: ""
            val money = when {
                invitationCode.startsWith(walletArl) -> arlBalance
                invitationCode.startsWith(walletCml) -> cmlBalance
                else -> cmlBalance
            }
            val bean = CMLIntent(
                address,
                money,
                selectorIcon(),
                selectorIcon(),
                CMLIntent.PARENT_ACCOUNT
            )
            start(CMLCollectionFragment.newInstance(bean))
        }

        //转账
        val transfer: View = inflate.findViewById(R.id.transfer)
        transfer.setOnClickListener {
            val address = sys ?: ""

            val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
            val invitationCode = userInfo?.invitationCode ?: ""
            val money = when {
                invitationCode.startsWith(walletArl) -> arlBalance
                invitationCode.startsWith(walletCml) -> cmlBalance
                else -> cmlBalance
            }

            val bean = CMLIntent(
                address,
                money,
                selectorIcon(),
                selectorIcon(),
                CMLIntent.PARENT_ACCOUNT
            )
            start(CMLTransferFragment.newInstance(bean))
        }


        mFooter.removeAllViews()
        addFooter(R.layout.sub_account_list_foot_fragment)
        mFooter.findViewById<View>(R.id.createAccount)
            .setOnClickListener {
                start(CreateSubAccountFragment.newInstance())
            }

        mRecyclerView.overScrollMode = View.OVER_SCROLL_NEVER

        mAdapter.addChildClickViewIds(R.id.transfer, R.id.mCopyTv, R.id.souKan)

        mAdapter.setOnItemChildClickListener(this)
    }

    //合成母币
    private fun onCompoundTv(item: ParentAccountBean?) {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val payPasswd = userInfo?.payPasswd ?: ""
        if (payPasswd.isEmpty()) {
            Toast.makeText(_mActivity, "请设置支付密码", Toast.LENGTH_SHORT).show()
            return
        }
        item?.cmlBalance = cmlBalance
        item?.arlBalance = arlBalance
        item?.scmlBalanceMixAvailable = scmlBalanceMixAvailable
        item?.cmlBalanceMixAvailable = cmlBalanceMixAvailable
        val pop = CompoundIconPop(_mActivity).setData(item)

        XPopup.Builder(_mActivity)
            .hasShadowBg(false)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    if (pop.dataSend) {
                        if (!mSwipeRefreshLayout.isRefreshing) {
                            mSwipeRefreshLayout.isRefreshing = true
                        }
                        onRefresh()
                    }

                    if (pop.mMoneyEmptyV) {
                        start(MainFragment.newInstance(), SINGLETASK)
//                        start(MainFragment.newInstance(),SINGLETOP)
                        EventBus.getDefault().post(MessageWrap.getInstance(SHOW_BUYING_PAGE_CML))
//                        val mainFragment = findFragment(MainFragment::class.java)
//                        if (mainFragment != null) {
//
//                        }
                    }
                }
            })
            .moveUpToKeyboard(true)
            .asCustom(pop)
            .show()
    }

    private fun onActive(position: Int) {
        val mBean = mXGridLayoutAdapter?.data?.get(position)
        if ((mBean?.balance ?: 0.0) <= 0.0) {
            Snackbar.make(
                rootView, "暂无可激活的母币",
                Snackbar.LENGTH_LONG
            )
                .addCallback(object : Snackbar.Callback() {
                    override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                        super.onDismissed(transientBottomBar, event)
                        onActive = false
                    }
                })
                .show()
            onActive = false
            return
        }
        Snackbar.make(
            rootView, "激活母币需要冻结${activeScmlLockNeedCmlNums}CML子币",
            Snackbar.LENGTH_LONG
        )
            .addCallback(object : Snackbar.Callback() {
                override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                    super.onDismissed(transientBottomBar, event)
                    onActive = false
                }
            })
            .setAction("确定") {
                sendOnActive(position)
            }
            .show()


    }

    private fun sendOnActive(position: Int) {
        val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "uid" to userInfo?.uid,
            "deviceToken" to deviceTokens
        )
        RestClient.builder()
            .url(R.string.activeScml)
            .raw(JSON.toJSONString(maps))
            .success {
                onActive = false
                Toast.makeText(_mActivity, "激活成功", Toast.LENGTH_SHORT).show()
                if (!mSwipeRefreshLayout.isRefreshing) {
                    mSwipeRefreshLayout.isRefreshing = true
                }
                onRefresh()
            }.failure {
                onActive = false
                Toast.makeText(_mActivity, "激活失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                onActive = false
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()

            }
            .build()
            .post()
    }

    override fun getItemLayout(): Int {
        return R.layout.sub_account_list_fragment
    }

    override fun convertItem(helper: JssBaseViewHolder?, item: SubAccountListBean?) {

        val statusStr = if (item?.accountStatus == 0) "矿工 （未激活）" else "矿工 （已激活）"

        helper?.setText(R.id.accountName, item?.accountName)
            ?.setText(R.id.status, statusStr)
            ?.setText(R.id.walletAddressTv, item?.walletAddress)
            ?.setText(R.id.interestTv, "累计生息 ${item?.cmlIncome} ${item?.tokenType}")
            ?.setText(R.id.holder, "持有 ${item?.tokenType} ${item?.cmlBalance}")
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(SubAccountListBean::class.java).endSubType().build()
    }

    override fun netRequest() {

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .url(R.string.queryChindAccountList)
            .raw(JSON.toJSONString(maps))
            .success {
                parseDate(it)

            }.failure {
                onFailed()
            }.error { _, _ ->
                onFailed()
            }
            .build()
            .post()
    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)
        val obj = JSON.parseObject(data)

        val childAccList = obj["childAccList"]

        val array = JSON.parseArray(JSON.toJSONString(childAccList), SubAccountListBean::class.java)

        loadListDate(array)

        cmlBalance = obj["cmlBalance"].toString()

        cmlBalanceLock = obj["cmlBalanceLock"].toString()

        arlBalance = obj["arlBalance"].toString()

        activeScmlLockNeedCmlNums = obj["activeScmlLockNeedCmlNums"].toString()

        scmlBalanceMixAvailable = obj["scmlBalanceMixAvailable"].toString()

        cmlBalanceMixAvailable = obj["cmlBalanceMixAvailable"].toString()

        isActiveScml=obj["isActiveScml"].toString()

//        val list = obj["list"] ?: ""
//
//        val motherAccountArray =
//            JSON.parseArray(JSON.toJSONString(list), ParentAccountBean::class.java)
//
//
//        mXGridLayoutAdapter?.clear()
//
//        mXGridLayoutAdapter?.addAll(motherAccountArray)
//
//        mXGridLayout.maxItem = motherAccountArray.size

        val addChildWalletCost = obj["addChildWalletAddrCost"].toString()

        val addChildWalletFee = obj["addChildWalletAddrFee"].toString()

        val feeBeanBean = BalanceInfoManager.mBalanceInfoManager.getFeeBeanBean()
        feeBeanBean?.addChildWalletAddrCost = addChildWalletCost
        feeBeanBean?.addChildWalletAddrFee = addChildWalletFee
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val invitationCode = userInfo?.invitationCode ?: ""
        when {
            invitationCode.startsWith(walletCml) -> {
                val arl = if (arlBalance.toDouble() > 0) "\n$walletArl $arlBalance" else ""
                walletTv.text = "$walletCml 可用：$cmlBalance  \n$walletCml 冻结：$cmlBalanceLock$arl"
            }
            invitationCode.startsWith(walletArl) -> {

                val cml = if (cmlBalance.toDouble() > 0)
                    "$walletCml 可用：$cmlBalance  \n$walletCml 冻结：$cmlBalanceLock \n" else ""

                walletTv.text = "$cml$walletArl $arlBalance"
            }
        }

    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

        val item = mAdapter.getItem(position)
        when (view.id) {
            R.id.mCopyTv -> {
                clipboard("item", item.walletAddress)
            }
            R.id.transfer -> {
                val address = item.walletAddress
                val bean =
                    CMLIntent(
                        address,
                        item.cmlBalance.toString(),
                        item.tokenType,
                        item.tokenType,
                        CMLIntent.CHILD_ACCOUNT
                    )
                start(CMLTransferFragment.newInstance(bean))
            }
            R.id.souKan -> {
                val address = item.walletAddress
                val bean =
                    CMLIntent(
                        address,
                        item.cmlBalance.toString(),
                        item.tokenType,
                        item.tokenType,
                        CMLIntent.CHILD_ACCOUNT
                    )
                start(CMLCollectionFragment.newInstance(bean))
            }
        }
    }

    override fun handMessage(msg: MessageWrap?) {
        super.handMessage(msg)
        if (msg?.message == TO_REFRESH_LIST) {
            if (!mSwipeRefreshLayout.isRefreshing) {
                mSwipeRefreshLayout.isRefreshing = true
            }
            onRefresh()
        }
    }
}